package com.magupe.develop.sm4;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.http.HttpUtil;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;

public class GetUserInfoTests {

    public static String APP = "1e89e6504be349a68c025976b3ecc1d1";
    public static String KEY = "859029d8956a44a6a47e2014e6882c1a";

    // 获取用户信息测试业务数据
    public static String CONTENT = "{\n" +
            "  \"token\": \"123\"\n" +
            "}";

    // 测试请求地址
    public static String URL = "http://123.160.220.48:10001/app/gateway/api/sso/token";

    public static void main(String[] args) {
        // 获取封装过的路径
        String url = getUrl();
        // 对业务数据加密
        String cons = Base64.getEncoder().encodeToString(SmUtil.sm4(HexUtil.decodeHex(KEY)).encrypt(CONTENT));
        // 发送请求
        String body = HttpUtil.createPost(url).contentType("application/json").body(cons).execute().body();
        // 对返回数据进行解密
        byte[] decrypt = SmUtil.sm4(HexUtil.decodeHex(KEY)).decrypt(body);

        System.out.println(new String(decrypt, StandardCharsets.UTF_8));
    }

    public static String getUrl(){
        // 获取随机值
        String nonce = UUID.randomUUID().toString().replaceAll("-", "");
        // 获取时间戳
        String timestamp = System.currentTimeMillis() + "";

        StringBuilder stringBuilder = new StringBuilder().append("app=").append(APP).append("&content=").append(CONTENT)
                .append("&key=").append(KEY).append("&nonce=").append(nonce).append("&timestamp=").append(timestamp);
        // 获取sign值
        String sign = SmUtil.sm3(stringBuilder.toString());
        // 拼装url中的参数
        StringBuilder sb = new StringBuilder().append("app=").append(APP).append("&content=").append(CONTENT)
                .append("&nonce=").append(nonce).append("&sign=").append(sign).append("&timestamp=").append(timestamp);
        // 获取最终访问路径
        String url = URL + "?"+sb.toString();
        return url;
    }
}
